import Taro, { Chain, RequestParams } from '@tarojs/taro';
import { baseUrl } from '../config';
import { HTTP_STATUS } from '../constant/http';
import useUserStore from '../stores/user';

/**
 * 超时时间，单位为毫秒
 * @default 2000
 */
const timeout = 10000;

/**
 * 平台标识
 * weapp: 小程序
 */
const platform = 'h5';

const authPrefix = 'Bearer ';


/**
 * 请求响应状态过滤器
 * @param chain 链
 * @returns 请求响应
 */
function codeInterceptor(chain) {
  const requestParams = chain.requestParams;
  return chain.proceed(requestParams).then((res: RequestParams) => {
    if (!res.data || !res.data.code) {
      Taro.showToast({ title: '请求失败 :-(', icon: 'none' });
      return Promise.reject('请求失败');
    }
    switch (res.data.code) {
      case HTTP_STATUS.SUCCESS:
        return res.data;
      case HTTP_STATUS.NOT_FOUND:
        Taro.showToast({ title: '请求资源不存在 :-(', icon: 'none' });
        return Promise.reject('请求资源不存在');
      case HTTP_STATUS.SERVER_ERROR:
        Taro.showToast({ title: res.data.msg, icon: 'none', duration: 3000 });
        return Promise.reject('服务端出现了问题');
      case HTTP_STATUS.FORBIDDEN:
        Taro.showToast({ title: '没有权限访问 :-(', icon: 'none' });
        return Promise.reject('没有权限访问');
      case HTTP_STATUS.AUTHENTICATE:
        const userStore = useUserStore();
        if (!userStore.readyToLogin) {
          Taro.showToast({ title: '需要鉴权，请先登录', icon: 'none' });
          userStore.readyToLogin = true;
          setTimeout(() => {
            Taro.redirectTo({ url: '/pages/login/index' });
          }, 1000);
        }
        return Promise.reject('需要鉴权');
      default:
        Taro.showToast({ title: '请求失败 :-(', icon: 'none' });
        return Promise.reject('未知状态码 ' + res.data.code);
    }
  });
}

/**
 * 添加过滤器
 */
Taro.addInterceptor(Taro.interceptors.timeoutInterceptor);
Taro.addInterceptor(Taro.interceptors.logInterceptor);
Taro.addInterceptor(codeInterceptor);

/**
 * 基本请求
 * @param params 请求参数
 * @param method 请求类型
 * @returns 返回值
 */
function baseRequest(params: any, method: any) {
  let { url, data } = params;
  return new Promise((resolve, reject) => {
    if (url == '/system/dept/getAllDataTree' || url.includes('/system/dict/data/type/')) {

    } else {
      Taro.showLoading({
        title: '加载中',
      });
    }


    Taro.request({
      url: baseUrl + url,
      data: {
        platform,
        ...data,
      },
      method,
      timeout,
      header: getHeader(params),
      success: function (res) {
        resolve(res.data);
      },
      fail: function (err) {
        Taro.showModal({
          title: '提示',
          showCancel: false,
          content: err.errMsg,
        });
        reject(err);
      },
      complete: () => {
        Taro.hideLoading();
      },
    });
  });
}

function getHeader(params) {
  const contentType = params.contentType || 'application/json;charset=UTF-8';
  let Authorization = '';
  const userStore = useUserStore();
  if (userStore.token) {
    Authorization = authPrefix + userStore.token;
  }
  return { contentType, Authorization };
}

function get(url: string, data?: any) {
  return baseRequest({ url, data }, 'GET');
}

function post(url: string, data?: any) {
  return baseRequest({ url, data }, 'POST');
}

function put(url: string, data: any) {
  return baseRequest({ url, data }, 'PUT');
}

function del(url: string, data?: any) {
  return baseRequest({ url, data }, 'DELETE');
}

const request = {
  get,
  post,
  put,
  del,
};

export default request;
